package com.cheng.example.excel.easyexcel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.NumberFormat;

/**
 * String and number converter
 *
 * @author Jiaju Zhuang
 */
public class StringNumberConverter implements Converter<String> {

    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        Object obj;
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            //判断是否是公式
            if (cellData.getFormula()){
                numberFormat.setMaximumFractionDigits(12);//小数点后保留几位
            }else {
                numberFormat.setMaximumFractionDigits(30);//小数点后保留几位
            }
            numberFormat.setGroupingUsed(false);//解决大于1000 的数时，有逗号问题
            obj = numberFormat.format(cellData.getNumberValue().doubleValue());
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            obj = String.valueOf(cellData.getStringValue());
        } else if (cellData.getType() == CellDataTypeEnum.BOOLEAN) {
            obj = Boolean.valueOf(cellData.getBooleanValue());
        } else if (cellData.getType() == CellDataTypeEnum.EMPTY) {
            obj = Boolean.valueOf(cellData.getBooleanValue());
        } else {
            obj = "";
        }

        if (obj instanceof String) {
            String str = (String) obj;
            str = StringUtils.replace(str, "　", "").trim();
            obj = str;
        }

        return String.valueOf(obj);
    }

    @Override
    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        return new CellData(new BigDecimal(value));
    }
}
